import {
  login,
  logout,
  // getUserInfo
} from "@/api/user";
import { setToken, removeToken, getToken } from "@/utils/auth";
import { resetRouter } from "@/router";

const state = {
  token: getToken() || "",
  userInfo: {
    username: "",
    avatar: "",
    id: "",
    sex: "",
  },
  nameList: JSON.parse(localStorage.getItem("nameList")) || [
    "杨军",
    "袁鹏",
    "殷明浩",
    "朱继翔",
    "雷道安",
    "姜新科",
    "黎少阳",
    "李荣文",
  ],
};
const mutations = {
  setToken(state, newToken) {
    state.token = newToken;
    setToken(newToken);
  },
  delToken(state) {
    state.token = "";
    removeToken();
  },
  setUserInfo(state, newUserInfo) {
    state.userInfo = newUserInfo;
  },
  delUserInfo(state) {
    state.userInfo = {
      username: "",
      avatar: "",
      id: "",
      sex: "",
    };
  },
  // 添加名字
  ADD_NAME(state, newName) {
    state.nameList.push(newName);
    localStorage.setItem("nameList", JSON.stringify(state.nameList));
  },
  REMOVE_NAME(state, name) {
    state.nameList = state.nameList.filter((item) => item !== name);
    localStorage.setItem("nameList", JSON.stringify(state.nameList)); // 同步到 localStorage
  },
  SET_NAMES(state, nameList) {
    state.nameList = nameList; // 设置名字列表
  },
};

const actions = {
  // 登录
  async loginAction(context, form) {
    const res = await login(form);
    let userInfo = {
      username: res.data?.username,
      avatar: res.data?.avatar || "",
      id: res.data?.id || "",
      sex: res.data?.sex || "",
    };
    context.commit("setToken", res.data?.token);
    context.commit("setUserInfo", userInfo);
    return res;
  },

  //  async getUserInfo(context) {
  //     const res1 = await getUserInfo()
  //     context.commit('setUserInfo', res1)
  //     return res1
  //   },

  async logout(context) {
    context.commit("delToken");
    context.commit("delUserInfo");
    // await logout()
    resetRouter();
  },
  // 添加名字
  addName({ commit }, newName) {
    commit("ADD_NAME", newName);
  },
  removeName({ commit }, name) {
    commit("REMOVE_NAME", name); // 提交删除名字的 mutation
  },
  loadNames({ commit }) {
    const nameList = JSON.parse(localStorage.getItem("nameList")) || nameList; // 加载 names
    commit("SET_NAMES", nameList); // 使用 mutation 设置到 store
  },
};

export default {
  namespaced: true,
  state,
  mutations,
  actions,
};
